// @Author : zaniu(zzaniu@126.com)
// @Time   : 2021/9/5 21:30
// @Desc   :
//
//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
// =====`-.____`-.___\_____/___.-`____.-'=====
//                   `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//           佛祖保佑       永无BUG
//
package order

import (
	"context"
	"distributedTransaction/client/conf"
	"distributedTransaction/proto2go"
	"distributedTransaction/utils/client"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"io/ioutil"
	"net/http"
)

type List []gin.H

type orderInfo struct {
	GoodsName   string `json:"goodsName"`
	GoodsNumber uint64 `json:"goodsNumber"`
}

// 这里有点问题啊，这里返回回去之后，GRPC和RocketMQ都关闭了，后续触发不了回查的啊
func PlaceOrder(ctx *gin.Context) {
	userName := ctx.GetString("user")
	order := orderInfo{}
	body, _ := ioutil.ReadAll(ctx.Request.Body)
	err := json.Unmarshal(body, &order)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"message": "请求参数错误", "token": ""})
		return
	}
	globalNo, err := client.PlaceOrder(client.Rocket, userName, order.GoodsName, order.GoodsNumber)
	if err != nil {
		fmt.Printf("下单失败, 请稍后重试。 err = %v\n", err.Error())
		ctx.JSON(http.StatusOK, gin.H{"message": err.Error(), "globalNo": globalNo})
	} else {
		fmt.Printf("下单成功, 订单流水号`%s`\n", globalNo)
		ctx.JSON(http.StatusOK, gin.H{"message": "下单成功", "globalNo": globalNo})
	}
}

func QueryOrder(ctx *gin.Context) {
	globalNo := ctx.Param("globalNo")
	if len(globalNo) > 0 {
		fmt.Println("暂未实现")
		ctx.JSON(http.StatusOK, gin.H{"message": "查询成功", "globalNo": globalNo})
	} else {
		rpcServerInfo, err := conf.GetOneRpcServerInfo(conf.GlobalOrderServices)
		if err != nil {
			panic(err)
		}
		orderConn, err := grpc.Dial(fmt.Sprintf("%s:%d", rpcServerInfo.Ip, rpcServerInfo.Port), grpc.WithInsecure())
		if err != nil {
			panic("grpc.Dial err:" + err.Error())
		}
		defer orderConn.Close()
		orderClient := proto2go.NewOrderClient(orderConn)
		tmp, err := orderClient.QueryOrder(context.Background(), &proto2go.QueryOrderRequest{UserName: ctx.GetString("user")})
		ret := List{}
		retMessage := "查询成功"
		if err != nil {
			st, ok := status.FromError(err)
			if ok && st.Code() == codes.NotFound {
				retMessage = "未查询到订单"
			} else {
				retMessage = "查询异常，请稍后重试"
			}
			ctx.JSON(http.StatusOK, gin.H{"message": retMessage, "info": ret})
			return
		}
		for index, info := range tmp.Order {
			ret = append(ret, gin.H{"index": index, "globalNo": info.GlobalNo, "userName": info.UserName, "goodsName": info.GoodsName, "goodsNumber": info.GoodsNumber})
		}
		ctx.JSON(http.StatusOK, gin.H{"message": retMessage, "info": ret})
	}
}
